import { MaterialItem, addMaterial } from '@/services/material';
import type { ProFormInstance } from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormDatePicker,
  ProFormDigit,
  ProFormText,
} from '@ant-design/pro-components';
import { message } from 'antd';
import { useRef } from 'react';

export type MaterialModalProps = {
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  initialValues?: Partial<MaterialItem>;
  onSuccess: () => void;
};

const MaterialModal: React.FC<MaterialModalProps> = ({
  visible,
  onVisibleChange,
  initialValues,
  onSuccess,
}) => {
  const formRef = useRef<ProFormInstance>();

  return (
    <ModalForm<Omit<MaterialItem, 'id' | 'sales'>>
      formRef={formRef}
      title={initialValues ? '编辑原料' : '新增原料'}
      open={visible}
      onOpenChange={onVisibleChange}
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      initialValues={initialValues}
      preserve={false}
      onFinish={async (values) => {
        try {
          let res;
          //新增
          res = await addMaterial(values);

          if (res.success) {
            message.success(initialValues ? '编辑成功' : '新增成功');
            onSuccess();
            return true;
          }
          return false;
        } catch (error) {
          message.error('新增失败');
          return false;
        }
      }}
    >
      <ProFormText
        name="goodsName"
        label="商品名称"
        placeholder="请输入商品名称"
        rules={[{ required: true, message: '请输入商品名称' }]}
      />
      <ProFormText
        name="supplierName"
        label="供应商"
        placeholder="请输入供应商名称"
        rules={[{ required: true, message: '请输入供应商名称' }]}
      />
      <ProFormText
        name="principal"
        label="负责人"
        placeholder="请输入负责人姓名"
        rules={[{ required: true, message: '请输入负责人姓名' }]}
      />
      <ProFormText
        name="place"
        label="产地"
        placeholder="请输入产地"
        rules={[{ required: true, message: '请输入产地' }]}
      />
      <ProFormDigit
        name="quantity"
        label="数量(KG)"
        placeholder="请输入数量"
        min={0}
        rules={[{ required: true, message: '请输入数量' }]}
      />
      <ProFormDigit
        name="price"
        label="价格"
        placeholder="请输入价格"
        min={0}
        rules={[{ required: true, message: '请输入价格' }]}
      />
      <ProFormDatePicker width="md" name="date" label="采购日期" />
    </ModalForm>
  );
};

export default MaterialModal;
